package com.example.redis.service;

import com.example.redis.exception.IdempotentException;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
public class TokenService {

    @Autowired
    RedisService redisService;

    public String createToken(){
        String uuid = UUID.randomUUID().toString();
        redisService.setExp(uuid,uuid, 10);
        return uuid;
    }

    public boolean checkToken(HttpServletRequest request) throws IdempotentException{
        String token = request.getHeader("token");
        if(StringUtil.isNullOrEmpty(token)){
            token = request.getParameter("token");
            if(StringUtil.isNullOrEmpty(token)){
                throw new IdempotentException("token不存在！");
            }
        }

        if(!redisService.exist(token)){
            throw new IdempotentException("token不存在！");
        }

        boolean removeFlag = redisService.remove(token);
        if(!removeFlag){
            throw new IdempotentException("token删除失败！");
        }
        return  removeFlag;
    }
}
